/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBeans;

import SessionBeans.UserSessionBean;
import entities.User;
import java.io.IOException;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import security.Md5;

/**
 *
 * @author Tomas
 */
@ManagedBean(name = "userManagedBean")
@SessionScoped
public class UserManagedBean implements Serializable {

    @EJB
    private UserSessionBean userSessionBean;
    private User user;
    private String userName;
    private String password;

    /**
     * Creates a new instance of NewJSFManagedBean
     */
    public UserManagedBean() {
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {

        this.user = user;
    }

    public boolean isLoggedIn() {
        if (user == null) {
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            user = (User) session.getAttribute("user");
        }
        return user != null;
    }

    public String logout() {
        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        session.removeAttribute("user");
        user = null;
        return "index1.xhtml?faces-redirect=true";
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String logIn() {
        String pass = Md5.MD5(password);
        if (userSessionBean.tryLogin(userName, pass)) {
            user = userSessionBean.login(userName, pass);
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
            session.setAttribute("user", user);
            session.setAttribute("userManagedBean", this);
            return "files.xhtml?faces-redirect=true";
        }
        return "index1.xhtml?faces-redirect=true";
    }

    public void checkAlreadyLoggedin() throws IOException {
        if (isLoggedIn()) {
            FacesContext.getCurrentInstance().getExternalContext().redirect("faces/files.xhtml");
        }
    }
}
